package com.example.mybaseapp.util.audiorecordutil;

import android.annotation.SuppressLint;
import android.media.AudioFormat;
import android.media.AudioRecord;
import android.media.MediaRecorder;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import java.util.Objects;

public class ContinuousAudioRecorder {

    private static final int RECORDER_SAMPLE_RATE = 44100;
    private static final int RECORDER_CHANNELS = AudioFormat.CHANNEL_IN_STEREO;
    private static final int RECORDER_AUDIO_ENCODING = AudioFormat.ENCODING_PCM_16BIT;
    private static final int RECORDER_BUFFER_SIZE = AudioRecord.getMinBufferSize(RECORDER_SAMPLE_RATE, RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING);

    private boolean isRecording = false;

    public void startRecordingAndReturnAudioData(final AudioDataCallback callback) {
        isRecording = true;

        final byte[] audioData = new byte[RECORDER_BUFFER_SIZE];

        @SuppressLint("MissingPermission") final AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC, RECORDER_SAMPLE_RATE, RECORDER_CHANNELS, RECORDER_AUDIO_ENCODING, RECORDER_BUFFER_SIZE);
        audioRecord.startRecording();

        Handler handler = new Handler(Objects.requireNonNull(Looper.myLooper()));
        handler.post(new Runnable() {
            @Override
            public void run() {
                while (isRecording) {
                    audioRecord.read(audioData, 0, RECORDER_BUFFER_SIZE);

                    // 返回录音数据
                    callback.onAudioData(audioData);
                }
                Log.d("ContinuousAudioRecorder", "run: 结束录音数据获取");
            }
        });
    }

    public void stopRecording() {
        isRecording = false;
    }

    public interface AudioDataCallback {
        void onAudioData(byte[] audioData);
    }

//    public static void main(String[] args) {
//        ContinuousAudioRecorder recorder = new ContinuousAudioRecorder();
//
//        // 开始录音并返回录音数据
//        recorder.startRecordingAndReturnAudioData(new AudioDataCallback() {
//            @Override
//            public void onAudioData(byte[] audioData) {
//                // 处理返回的音频数据
//                Log.d("ContinuousAudioRecorder", "Received audio data: " + audioData.length + " bytes");
//            }
//        });
//
//        // 一段时间后停止录音
//        Handler stopHandler = new Handler();
//        stopHandler.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                recorder.stopRecording();
//            }
//        }, 10000); // 这里在10秒后停止录音
//    }
}